<?php
namespace App\Services;

use App\Models\UserPush;
use Illuminate\Support\Facades\Log;
use JPush\Exceptions\APIConnectionException;
use JPush\Exceptions\APIRequestException;

/**
 *
 * 推送通知服务层
 *
 * @author maqu
 *
 */
class NotificationService extends BaseService {

    /**
     * Jpush推送注册
     *
     * @param $user_id
     * @param $registrationid
     */
    public function register($user_id,$registrationid){

        $userPush = UserPush::findOrNew($user_id);
        $userPush->user_id = $user_id;
        $userPush->registrationid =$registrationid;
        $userPush->save();

    }

    /**
     * Jpush推送清除
     *
     * @param $ids
     */
    public function clear($ids){

        if(is_array($ids)) {

            $pushs = UserPush::whereIn('user_id',$ids);
            foreach($pushs as $v){
                $v->delte();
            }
        } else {
            $push =UserPush::find($ids);
            if($push){
                $push->delete();
            }
        }

    }

    public function sendByRegistrationId($registrationids,$content,$extraInfos){

        $master_secret = config('maqu.JPUSH_MASTER_SECRET');
        $app_key=config('maqu.JPUSH_APPKEY');
        $br = '\n ';

        $client = new \JPush\Client($app_key, $master_secret);

        //easy push
        try {
            $count = count($registrationids);
            $times = intval(ceil($count/1000));

            $tempids =[];

            for($i=0;$i<$times;$i++){

                $tempids = array_slice($registrationids,$i*1000,($count -$i*1000)>=1000?1000:$count -$i*1000);

                $result = $client->push()
                    ->setPlatform('all')
                    ->addRegistrationId($tempids)
                    ->setNotificationAlert($content)
                    ->addAndroidNotification($content, null, null,null,$extraInfos)
                    ->addIosNotification($content, null, \JPush\Config::DISABLE_BADGE, true,null, $extraInfos)
                    ->setMessage($content,null, null, $extraInfos)
                    ->send();

            }

            Log::debug('Push Success.' . $br);
            Log::debug('sendno : ' . $result->sendno . $br);
            Log::debug('msg_id : ' .$result->msg_id . $br);
            Log::debug('Response JSON : ' . $result->json . $br);

            $emsg = 'Push Success.' . $br.'Http Code : ' . 'sendno : ' . $result->sendno . $br.'msg_id : ' .$result->msg_id . $br.'Response JSON : ' . $result->json;
            Log::debug($emsg);

            unset($master_secret,$app_key,$client,$logger,$count,$times,$tempids);

            $this->success(null);
        } catch (APIRequestException $e) {

            $emsg = 'Push Fail: ' . $br.'Http Code : ' . $e->getHttpCode() . $br.'code : ' . $e->getCode() . $br.'Error Message : ' . $e->getMessage();
            Log::error($emsg);

            unset($master_secret,$app_key,$client,$logger,$count,$times,$tempids);

            $this->failure('推送失败');

        } catch (APIConnectionException $e) {

            $emsg = 'Push Fail: ' . $br.'Http Code : ' . $e->getHttpCode() . $br.'code : ' . $e->getCode() . $br.'Error Message : ' . $e->getMessage();
            Log::error($emsg);

            unset($master_secret,$app_key,$client,$logger,$count,$times,$tempids);

            $this->failure('推送失败');
        }

    }


    public function sendByAlias($alias,$content,$extraInfos){

        $master_secret = config('maqu.JPUSH_MASTER_SECRET');
        $app_key=config('maqu.JPUSH_APPKEY');
        $br = '\n ';

        $client = new \JPush\Client($app_key, $master_secret);

        //easy push
        try {
            $count = count($alias);
            $times = intval(ceil($count/1000));

            $tempids =[];
            if($count > 0 ){
                foreach($alias as $k=> $item){
                    $nalias[$k] = (String)$item;
                }
            }

            for($i=0;$i<$times;$i++){

                $tempids = array_slice($nalias,$i*1000,($count -$i*1000)>=1000?1000:$count -$i*1000);

                $result = $client->push()
                    ->setPlatform('all')
                    ->addAlias($tempids)
                    ->setNotificationAlert($content)
                    ->addAndroidNotification($content, null, null,null,$extraInfos)
                    ->addIosNotification($content, null, \JPush\Config::DISABLE_BADGE, true,null, $extraInfos)
                    ->setMessage($content,null, null, $extraInfos)
                    ->send();

                $emsg = 'Result=' . json_encode($result) . $br;
                Log::debug($emsg);
            }

            unset($master_secret,$app_key,$client,$logger,$count,$times,$tempids);

            $this->success(null);
        } catch (APIRequestException $e) {

            $emsg = 'Push Fail: ' . $br.'Http Code : ' . $e->getHttpCode() . $br.'code : ' . $e->getCode() . $br.'Error Message : ' . $e->getMessage();
            Log::error($emsg);

            unset($master_secret,$app_key,$client,$logger,$count,$times,$tempids);

            $this->failure('推送失败');

        } catch (APIConnectionException $e) {

            $emsg = 'Push Fail: ' . $br.'Http Code : ' . $e->getHttpCode() . $br.'code : ' . $e->getCode() . $br.'Error Message : ' . $e->getMessage();
            Log::error($emsg);

            unset($master_secret,$app_key,$client,$logger,$count,$times,$tempids);

            $this->failure('推送失败');
        }

    }

}